<?php
/**
 *
 *----------Dragon be here!----------/
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * Created by PhpStorm.
 * User: huangxh
 * Date: 2018/1/5 0005
 * Time: 上午 11:20
 */
use Yaf\Bootstrap_Abstract;

use Yaf\Dispatcher;
use Yaf\Application;
use Yaf\Request\Http;
use Yaf\Registry;
use Yaf\Session;
use models\Mysql\db;
use Yaf\Loader;
use Monolog\Logger;
use models\Redis\RedisManager;
use Monolog\Handler\StreamHandler;

class Bootstrap extends Bootstrap_Abstract
{
    /**
     * 导入composer
     */
    public function _initVendor()
    {
        require realpath(dirname(__FILE__)) . '/../vendor/autoload.php';
    }

    /**
     * 初始化session
     * @param Dispatcher $dispatcher
     */
    public function _initSession(Dispatcher $dispatcher)
    {
        Session::getInstance()->start();
    }

    /**
     * 设置日志
     */
    public function _initLog()
    {
        $db_log_path = realpath(dirname(__FILE__)) . '/../log/db/';        //sql执行日志
        $error_log__path = realpath(dirname(__FILE__)) . '/../log/error/';        //sql执行日志
//        $user_log_path = realpath(dirname(__FILE__)) . '/../log/user/';       //用户操作日志
//        $sms_log_path = realpath(dirname(__FILE__)) . '/../log/sms/';         //短信接口日志


        $log_file_success_name = "log_" . date('Y-m-d', time()) . ".log";
        $log_file_error_name = "error_" . date('Y-m-d', time()) . ".log";


        $db_file = new \Common\DirFileOperation($db_log_path . $log_file_success_name);

        if ($db_file->genFile() !== true) {
            $e = new Exception(str_replace('%s', $db_log_path . $log_file_success_name, \ErrorMsg\Admin\ErrorMsg::INITIALIZATION_LOG_FILE_FAILED), '001');
            throw $e;
        }

        $error_file = new \Common\DirFileOperation($error_log__path . $log_file_error_name);

        if ($error_file->genFile() !== true) {
            $e = new Exception(str_replace('%s', $error_log__path . $log_file_error_name, \ErrorMsg\Admin\ErrorMsg::INITIALIZATION_LOG_FILE_FAILED), '001');
            throw $e;
        }


/*        $log_file = new \Common\DirFileOperation($user_log_path . $log_file_name);
        if ($log_file->genFile() !== true) {
            $e = new Exception(str_replace('%s', $user_log_path . $log_file_name, \ErrorMsg\Admin\ErrorMsg::INITIALIZATION_LOG_FILE_FAILED), '001');
            throw $e;
        }

        $sms_file = new \Common\DirFileOperation($sms_log_path . $log_file_name);
        if ($sms_file->genFile() !== true) {
            $e = new Exception(str_replace('%s', $sms_log_path . $log_file_name, \ErrorMsg\Admin\ErrorMsg::INITIALIZATION_LOG_FILE_FAILED), '001');
            throw $e;
        }*/

        $db_log = new Logger("db");
        $error_log = new Logger("error");
/*        $user_log = new Logger("user");
        $sms_log = new Logger("sms");*/
        $db_log->pushHandler(new StreamHandler($db_log_path /*. '/' */ . $log_file_success_name), Logger::INFO);
        $error_log->pushHandler(new StreamHandler($error_log__path /*. '/' */ . $log_file_error_name), Logger::ALERT);

//        $user_log->pushHandler(new StreamHandler($user_log_path /*. '/'*/ . $log_file_name), Logger::WARNING);
//        $sms_log->pushHandler(new StreamHandler($sms_log_path /*. '/'*/ . $log_file_name), Logger::WARNING);

        Registry::set("db_log", $db_log);
        Registry::set("error_log", $error_log);
//        Registry::set("user_log", $user_log);
//        Registry::set("sms_log", $sms_log);
    }


    /**
     * 配置request参数与方法
     */
    public function _initParams(){
        $http = new Http();
        //设置全局的method变量
        Registry::set("method", $http->getMethod());
        $old_parameters = Registry::get("parameters");

        if ($http->isGet() === true) {
            $request_parameters = array_filter($http->getQuery());
        }elseif ($http->isPost() === true){
            $request_parameters = array_filter($http->getRequest());
        } else {
            $parameters = file_get_contents("php://input");
            parse_str($parameters, $request_parameters);
        }
        $parameters = $old_parameters && $request_parameters ? array_merge($old_parameters, $request_parameters) :
            ($old_parameters && ! $request_parameters ? $old_parameters :
                ($request_parameters && ! $old_parameters ? $request_parameters : [])
            );

        Registry::set("parameters", $parameters);
    }

    /**
     * 初始化配置文件
     */
    public function _initConfig() {
        $config = Application::app()->getConfig()->toArray();
        //判断路由配置文件是否存在，并合并配置文件
        if(! file_exists(APP_PATH . '/conf/route.ini')){
            exit("路由文件不存在");
        }
//        $route = new Yaf\Config\Ini(APP_PATH . '/conf/route.ini');

//        $config = array_merge($config, $route->toArray());
        Registry::set("config", $config);
        Dispatcher::getInstance()->autoRender(false);
    }

    /**
     * 路由配置
     */
   /* public function _initRouter(Dispatcher $dispatcher){
        $dispatcher->catchException(true);
        $router = $dispatcher->getRouter();
        $router->addConfig(Registry::get("config")['routes']);

    }*/

    /**
     * 实例化mysql数据库
     */
    public function _initDb()
    {

        $db = new db();
        Registry::set('conn',$db->initDb());

    }

    /**
     * 实例化redis
     */
    public function _initRedis()
    {
        require_once realpath(dirname(__FILE__)) . '/../application/models/Redis/RedisManager.php';
        $redis = new RedisManager([
                'schema' => 'tcp',
                'host' => Registry::get("config")['admin']['master']['redis']['host'],
                'port' => Registry::get("config")['admin']['master']['redis']['port'],
                /*'password' => Registry::get("config")['admin']['master']['redis']['passwd']*/
            ]
        );
        $redis->selectDb(Registry::get("config")['admin']['master']['redis']['select']);
        Registry::set("redis", $redis->getClient());
        Registry::set('rdm', $redis);
    }

    /**
     * 初始化插件
     * @param Dispatcher $dispatcher
     */
    public function _initPlugin(Dispatcher $dispatcher) {
        $user = new \Hooks\AdminMiddlewarePlugin();
        $dispatcher->registerPlugin($user);
    }
}